import base64
import os
from Crypto.Cipher import AES
from Crypto.Hash import  SHA256
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from openapi.models import Store
import datetime

from django.utils import timezone

import base64

from Crypto.Cipher import AES


def aes_test(data):
    iv = "ownmv0jV2LC2KROnq208gA=="
    key = "LHDhK3oGRvkiefQnx7OOczTY5Tic/xZ6HcMOc/gmtoM="
    cipher = AES.new(base64.b64decode(key), AES.MODE_CFB, iv=base64.b64decode(iv))
    return cipher.decrypt(base64.b64decode(data)).decode()

def aes_encrypt(data_list, key):
    '''
        input : key and data_list: utf-8 encoding
        output: iv and ct_list: base64, utf-8
    '''
    iv = os.urandom(16)
    key = base64.b64decode(key)
    ct_list = dict([(k, base64.b64encode(AES.new(key, AES.MODE_CFB, iv=iv).encrypt( str(data_list[k]).encode() )).decode()) for k in data_list])
    iv = base64.b64encode(iv).decode('utf-8')
    return iv, ct_list

def aes_decrypt(data_list, key, iv):
    '''
        input: key, iv and date_list:base64, utf-8 
        output: pt_list: utf-8
    '''
    key = base64.b64decode(key)
    iv = base64.b64decode(iv)
    pt_list = dict([(k, AES.new(key, AES.MODE_CFB, iv=iv).decrypt(base64.b64decode(data_list[k])).decode()) for k in data_list])
    return pt_list

def RSAtest():
    # store = Store.objects.get(id=1)
    store_private_key = "MIIEpAIBAAKCAQEAxYl31LELux9238JqEg/ZzBhxV8gGQ9horu9IkzzKHzNUryexANBpesJGliqQCDIBaEpD+fVpyXA4oUtvx9IQuZaReKQj2vpA0Dttaw7VcCQFAzn/Z1oZzJ2AiKC1GDYTkpQjfQMDjQZmx+fBY+DIGCGKj84i5lroZ5ioWTE3kL7v3+3HxT+2WmH7LBRYcKTaVhJJQcTJBxFNdYQ/mKTDjdUfVLPe8PzmlrN7YTer8i7Ow5xbodRG7GCDjJTahUvg+aFFL3mhS5SNzsRbqWGE9rTFUEFTuqQfBvp80RcrcndQc//PmmbV23mV2IngAbQk1Sj/HZcBoRUattIFWMfqxwIDAQABAoIBAHpMXN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m2rNqGbZny2nC+7PVSeYOFODKVGY31O6xW5DtAe/jxTEMlKKdcCgYA2MyWyQp5dNe+zpN9qr9bXFhc69N0MkYc8a5kmwrjK3c3ctPKFBgUDLk7dMBkMUmjJD1Wi3amJvFDq3Afcy0XF1bL/+nC6us7pmqiFJc1E2NaLLBrPY3fuUHJ5o+6z+UcgAWaa2h11MwwHBethOsA7nJh1ZgcGnvk2beuZaCH3TwKBgQCk1WEpueW318XwGWMcetWQRzzQ0AXNJfx+eoT+E0gGM+OQCdKd0DipC9F+u7CPL+v3JS+/kc8OkZbcD5f4IX1xt4tL9pR0tTyaLMcWJgBnVC/yhj5kk4ZfE2b2utXSx+d6hoWHxD5AuOVyk6+X6Ruh6qmL3MXxuFFXk1uf9ZRfEA=="
    params = dict({"store_id":1, "notify_url" : "http://www.zhihu.com", "return_url": "http://www.baidu.com",
                    "out_order_id" : "114514", "time_stamp" : datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "total_amount" : 0})
    store_signRsa = SignRSA(stonepay_public_key, store_private_key, params)
    sign = store_signRsa.rsa2sign(params)
    return params, sign

class SignRSA(object):
    def __init__(self, public_key, private_key, params):
        self.public_key = public_key
        self.private_key = private_key
        self.params = params
    '''
        传输的数据做处理
    '''
    def rsa2verify(self):
        # 获得签名
        sign = self.params.pop("sign", None)
        if self.params is None or sign is None:
            return False
        public_key_string = '-----BEGIN PUBLIC KEY-----\n' + self.public_key + '\n-----END PUBLIC KEY-----'
        sign_content = self.gen_sign_content(self.params)
        hash = SHA256.new(sign_content.encode()) # uft-8 -> byte
        signer = PKCS1_v1_5.new(RSA.importKey(public_key_string))
        result =  signer.verify(hash, base64.b64decode(sign)) # b64 -> byte
        return result
    def rsa2sign(self, params):
        private_key_string = '-----BEGIN PRIVATE KEY-----\n' + self.private_key + '\n-----END PRIVATE KEY-----' 
        sign_content = self.gen_sign_content(params)
        hash = SHA256.new(sign_content.encode()) # utf-8 -> byte
        signer = PKCS1_v1_5.new(RSA.importKey(private_key_string))
        sign = signer.sign(hash)
        return base64.b64encode(sign).decode() # utf-8
    def gen_sign_content(self, params):
        '''
            从k-v键值对生成准备加密的raw签名字符串
        '''
        raw = [(k, params[k]) for k in sorted(params.keys())]
        order_str = "&".join("=".join([k,str(v)]) for k, v in raw if v)
        return order_str